﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data;
using MySql.Data.MySqlClient;
using Contacts.Mail;
using System.Windows.Forms.ComponentModel;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Security.Principal;
using Microsoft.Office.Interop.Outlook;
using System.Configuration;


namespace Contacts
{
    public partial class Contacts : Form
    {
        #region Private Declarations

        /// <summary>
        /// Holds the data from the MySql server
        /// </summary>
        DataSet contacts;
        ContactsAddEdit contf;
        ContactMessage mess;
        BindingNavigator contactsbn = new BindingNavigator(true);
        BindingSource contactsbs = new BindingSource();
        BindingSource grvbs = new BindingSource();
        BindingSource project_contactsbs = new BindingSource();
        DataColumn projectsdc = new DataColumn();
        DataView pcview;
        MySqlConn connect = new MySqlConn();
        DataTable original = new DataTable();
        DataTable current = new DataTable();
        DataTable user;
        DataTable currentpc = new DataTable();
        DataRow pc;
        // olconn olc = new olconn();
        DataGridViewRow cr;
        public DataGridView datagrv;
        public int pos;
        private int pi;
        private int rc;
        private int pcid;
        private int strid;
        private int lpcid;
        private int rowinEdit = -1;
        private bool a;
        private bool m;
        private bool d;
        string tostr;
        string ccstr;
        string bcstr;
        int id;
        DateTime timeofpull = new DateTime();
        public string top;
        string db;
        private int jrid;
        private int cid;
        #endregion

        #region Ctor
        /// <summary>
        /// Empty constructor, use for debugging only
        /// </summary>
        public Contacts()
        {
            InitializeComponent();
        }
        #endregion

        /// <summary>
        /// Makes the connection to the MySql database specified in the config file.
        /// Then loads the data and builds relations between everything.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Contacts_Load(object sender, EventArgs e)
        {
            // begin loading the data
            try
            {                
                connect.Connect();
                connect.LoadContacts();                
                connect.Relations();
                connect.Disconnect();               
                contacts = connect.Data;
                timeofpull = DateTime.Now;
                top = timeofpull.ToLongTimeString();
                tbo_time.Text = top;
                tbo_time.Visible = false;
                GC.KeepAlive(connect);
            }
            catch (MySqlException me)
            {
                Mail.mailman.sendmail("MySql connection failed to load database", "Method: " + me.TargetSite + Environment.NewLine + "Error Message:" + Environment.NewLine
                    + me.Message + Environment.NewLine + "Call Stack:" + Environment.NewLine + me.StackTrace);
                throw new MySqlException("Connecting to Mysql Server had problems", me);
            }
            // end loading data

            datagrv = grd_jr_cont;

            // add additional columns
            DataColumn projsel = contacts.Tables["projects"].Columns.Add("str_sel");
            DataColumn fullname = contacts.Tables["contacts"].Columns.Add("full_name");
            DataColumn jrname = contacts.Tables["project_contacts"].Columns.Add("jr_name");
            DataColumn compsel = contacts.Tables["companies"].Columns.Add("comp_sel");
            // end column add            

            //this creates a store select so projects will be shown alphabetized by city name in project selector
            // of if the preferences allow, these are sorted by store number
            int i;
            int irc = contacts.Tables["projects"].Rows.Count;
            for (i = 0; i < irc; i++)
            {
                DataRow row = contacts.Tables["projects"].Rows[i];
                switch (Properties.Settings.Default.STORE_SORT)
                {
                    case "STORE":
                        row["str_sel"] = row["str_num"].ToString() + '-' + row["str_seq"] + ' ' + row["str_city"].ToString() + ' ' + row["str_st"].ToString();
                        break;

                    default:
                        row["str_sel"] = row["str_city"].ToString() + ' ' + row["str_st"].ToString() + ' ' + row["str_num"] + '-' + row["str_seq"];
                        break;
                }
            }

            //this creates a full name select so contacts will be shown alphabetized by first/last name in contact selector
            // or if preferences are set Last Name, First Name
            int j;
            int jrc = contacts.Tables["contacts"].Rows.Count;
            for (j = 0; j < jrc; j++)
            {
                DataRow row = contacts.Tables["contacts"].Rows[j];
                string mn = row["middle_name"].ToString();
                switch (Properties.Settings.Default.DISPLAY_NAME_ORDER)
                {
                    case "LAST":
                        if (String.IsNullOrEmpty(mn))
                            row["full_name"] = row["last_name"].ToString() + ", " + row["first_name"].ToString();
                        else
                            row["full_name"] = row["last_name"].ToString() + ", " + row["first_name"].ToString() + ' ' + row["middle_name"].ToString();
                        break;

                    default:
                        if (String.IsNullOrEmpty(mn))
                            row["full_name"] = row["first_name"].ToString() + ' ' + row["last_name"];
                        else
                            row["full_name"] = row["first_name"].ToString() + ' ' + row["middle_name"].ToString() + ' ' + row["last_name"];
                        break;
                }
            }

            //this creates a job role name so all records will be alphabetized by job role name in datagridview
            int k;
            int krc = contacts.Tables["project_contacts"].Rows.Count;
            for (k = 0; k < krc; k++)
            {
                object jrv = contacts.Tables["project_contacts"].Rows[k].ItemArray[2];
                DataRow jra = contacts.Tables["job_roles"].Rows.Find(jrv);
                DataRow row = contacts.Tables["project_contacts"].Rows[k];
                row["jr_name"] = jra.ItemArray[1].ToString();
            }

            //this creates a company name by location for selector in the contacts form
            int m;
            int mrc = contacts.Tables["companies"].Rows.Count;
            for (m = 0; m < mrc; m++)
            {
                DataRow row = contacts.Tables["companies"].Rows[m];
                row["comp_sel"] = row["company_name"] + ", " + row["street"] + ", " + row["city"] + ", " + row["state"];
            }

            //this establishes the contacts sort, valuemember, displaymember, and binds it
            contacts.Tables["contacts"].DefaultView.Sort = "full_name";
            contactsbs.DataSource = contacts;
            contactsbn.BindingSource = contactsbs;

            cbo_projects.ValueMember = "projects.str_id";
            cbo_projects.DisplayMember = "projects.str_sel";
            cbo_projects.DataSource = contactsbs;

            //this hides the 4 id's that make the datagridview work
            grd_jr_cont.Columns["project_contact_id"].Visible = false;
            grd_jr_cont.Columns["str_id"].Visible = false;
            grd_jr_cont.Columns["job_role_id"].Visible = false;
            grd_jr_cont.Columns["contact_id"].Visible = false;
            grd_jr_cont.Columns["jr_name"].Visible = false;

            lpcid = (int)contacts.Tables["project_contacts"].Rows[(contacts.Tables["project_contacts"].Rows.Count - 1)]["project_contact_id"];

            _isdirty = contacts.HasChanges();
        }

        //this allows the change in the project selector and re-fills the datagridview
        private void cbo_projects_SelectedIndexChanged(object sender, EventArgs e)
        {
            pi = cbo_projects.SelectedIndex;
            pcview = new DataView(contacts.Tables["project_contacts"]);
            pcview.RowFilter = string.Format("str_id = {0}", cbo_projects.SelectedValue);
            pcview.Sort = "jr_name";
            grd_jr_cont.DataSource = pcview;
            tbo_str_num.Text = contacts.Tables["projects"].Rows[pi]["str_num"].ToString();
            tbo_str_num.BackColor = Color.Aquamarine;
            tbo_str_seq.Text = contacts.Tables["projects"].Rows[pi]["str_seq"].ToString();
            tbo_str_seq.BackColor = Color.Aquamarine;
            tbo_str_city.Text = contacts.Tables["projects"].Rows[pi]["str_city"].ToString();
            tbo_str_city.BackColor = Color.Aquamarine;
            tbo_str_st.Text = contacts.Tables["projects"].Rows[pi]["str_st"].ToString();
            tbo_str_st.BackColor = Color.Aquamarine;
            cbo_job_roles.DataSource = contacts.Tables["job_roles"];
            cbo_job_roles.ValueMember = "job_role_id";
            cbo_job_roles.DisplayMember = "job_role";
            cbo_contacts.DataSource = contacts.Tables["contacts"];
            cbo_contacts.ValueMember = "contact_id";
            cbo_contacts.DisplayMember = "full_name";
            func.FillRows(contacts, grd_jr_cont);
            int nr = grd_jr_cont.NewRowIndex;
            grd_jr_cont.CurrentCell = grd_jr_cont.Rows[nr].Cells[0];
            grd_jr_cont.CurrentCell.Style.BackColor = grd_jr_cont.DefaultCellStyle.BackColor;
            grd_jr_cont.EditMode = DataGridViewEditMode.EditOnEnter;
        }

        //both the job role combo box and the contacts combo box are
        //cast into a combo box to do a selectindexchanged event
        
        private void grd_jr_cont_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox combo = e.Control as ComboBox;

            combo.AutoCompleteSource = AutoCompleteSource.ListItems;
            combo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

            if (combo != null)
            {
                combo.SelectionChangeCommitted -= new EventHandler(ComboBox_SelectionChangeCommitted);
                combo.SelectionChangeCommitted += new EventHandler(ComboBox_SelectionChangeCommitted);
            }
        }

        private void grd_jr_cont_RowHeaderMouseClick(object sender, EventArgs e)
        {
            grd_jr_cont.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }
        
        //this redefines the datagridview when either a change is made to the job role or contact
        private void ComboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            int cpcid = (int)grd_jr_cont.CurrentRow.Cells["project_contact_id"].Value;

            try
            {
                int ci = grd_jr_cont.CurrentCell.ColumnIndex;
                int cr = grd_jr_cont.NewRowIndex;
                string colname = grd_jr_cont.Columns[ci].HeaderText;
                int si = ((ComboBox)sender).SelectedIndex;
                bool jrnb = String.IsNullOrEmpty(grd_jr_cont.CurrentRow.Cells[0].FormattedValue.ToString());
                bool cnb = String.IsNullOrEmpty(grd_jr_cont.CurrentRow.Cells[1].FormattedValue.ToString());

                switch (colname)
                {
                    case "Job Role":
                        {
                            switch (cnb)
                            {
                                case true:
                                    {
                                        grd_jr_cont.CurrentRow.Cells["job_role_id"].Value = ((ComboBox)sender).SelectedValue;
                                        grd_jr_cont.CurrentRow.Cells["cbo_job_roles"].Value = grd_jr_cont.CurrentRow.Cells["job_role_id"].Value;
                                        jrid = (int)grd_jr_cont.CurrentRow.Cells["job_role_id"].Value;
                                        grd_jr_cont.CurrentRow.Cells["str_id"].Value = contacts.Tables["projects"].Rows[pi]["str_id"];
                                        DataRow jrn = contacts.Tables["job_roles"].Rows.Find(((ComboBox)sender).SelectedValue);
                                        grd_jr_cont.CurrentRow.Cells["jr_name"].Value = jrn["job_role"];                                        
                                    }
                                    break;
                                case false:
                                    {
                                        for (int i = 0; i < grd_jr_cont.Rows.Count - 2; i++)
                                        {
                                            if ((int)((ComboBox)sender).SelectedValue == (int)grd_jr_cont.Rows[i].Cells["job_role_id"].Value &&
                                                (int)grd_jr_cont.CurrentRow.Cells["contact_id"].Value == (int)grd_jr_cont.Rows[i].Cells["contact_id"].Value)
                                            {
                                                DataRow j = contacts.Tables["job_roles"].Rows.Find(((ComboBox)sender).SelectedValue);
                                                string jn = j.ItemArray[1].ToString();
                                                DataRow c = contacts.Tables["contacts"].Rows.Find(grd_jr_cont.Rows[i].Cells["contact_id"].Value);
                                                string cn = c.ItemArray[9].ToString();
                                                MessageBox.Show("A contact named " + cn +
                                                " has already been assigned to the job role " + jn + "!",
                                                "Assignment Already Exist", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                                ((ComboBox)sender).ResetText();
                                                grd_jr_cont.CurrentRow.Cells["job_role_id"].Value = "";
                                            }
                                        }
                                        grd_jr_cont.CurrentRow.Cells["job_role_id"].Value = ((ComboBox)sender).SelectedValue;
                                        grd_jr_cont.CurrentRow.Cells["cbo_job_role"].Value = grd_jr_cont.CurrentRow.Cells["job_role_id"].Value;
                                        grd_jr_cont.CurrentRow.Cells["str_id"].Value = contacts.Tables["projects"].Rows[pi]["str_id"];
                                        DataRow jrn = contacts.Tables["job_roles"].Rows.Find(((ComboBox)sender).SelectedValue);
                                        grd_jr_cont.CurrentRow.Cells["jr_name"].Value = jrn.ItemArray[1];
                                        grd_jr_cont.CurrentCell = grd_jr_cont.Rows[cr].Cells[0];                                        
                                    }
                                    break;
                            }
                        }
                        break;

                    case "Full Name":
                        {
                            int csi = ((ComboBox)sender).SelectedIndex;

                            switch (csi)
                            {
                                case -1:
                                    { }
                                    break;
                                case 0:
                                    {
                                        grd_jr_cont.CurrentRow.Cells["contact_id"].Value = ((ComboBox)sender).SelectedValue;
                                        grd_jr_cont.CurrentRow.Cells[5].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[6].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[7].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[8].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[9].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[10].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[11].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[12].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[13].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[14].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[15].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[16].Value = "";
                                        grd_jr_cont.CurrentRow.Cells[17].Value = "";
                                    }
                                    break;
                                default:
                                    {
                                        switch (jrnb)
                                        {
                                            case true:
                                                {
                                                    grd_jr_cont.CurrentRow.Cells["str_id"].Value = contacts.Tables["projects"].Rows[pi]["str_id"];
                                                    grd_jr_cont.CurrentRow.Cells["contact_id"].Value = ((ComboBox)sender).SelectedValue;
                                                    grd_jr_cont.CurrentRow.Cells["cbo_contacts"].Value = grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                                                    cid = (int)grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                                                    DataRow conta = contacts.Tables["contacts"].Rows.Find(((ComboBox)sender).SelectedValue);
                                                    DataRow compa = contacts.Tables["companies"].Rows.Find(conta.ItemArray[5]);
                                                    DataRow cata = contacts.Tables["categories"].Rows.Find(compa.ItemArray[9]);
                                                    grd_jr_cont.CurrentRow.Cells[5].Value = conta.ItemArray[4];
                                                    grd_jr_cont.CurrentRow.Cells[6].Value = compa.ItemArray[1];
                                                    grd_jr_cont.CurrentRow.Cells[7].Value = compa.ItemArray[2];
                                                    grd_jr_cont.CurrentRow.Cells[8].Value = compa.ItemArray[3];
                                                    grd_jr_cont.CurrentRow.Cells[9].Value = compa.ItemArray[4];
                                                    grd_jr_cont.CurrentRow.Cells[10].Value = compa.ItemArray[5];
                                                    grd_jr_cont.CurrentRow.Cells[11].Value = compa.ItemArray[6];
                                                    grd_jr_cont.CurrentRow.Cells[12].Value = conta.ItemArray[6];
                                                    grd_jr_cont.CurrentRow.Cells[13].Value = compa.ItemArray[7];
                                                    grd_jr_cont.CurrentRow.Cells[14].Value = compa.ItemArray[8];
                                                    grd_jr_cont.CurrentRow.Cells[15].Value = conta.ItemArray[7];
                                                    grd_jr_cont.CurrentRow.Cells[16].Value = conta.ItemArray[8];
                                                    grd_jr_cont.CurrentRow.Cells[17].Value = cata.ItemArray[1];                                                    
                                                }
                                                break;
                                            case false:
                                                {
                                                    for (int i = 0; i < grd_jr_cont.Rows.Count - 2; i++)
                                                    {
                                                        if ((int)((ComboBox)sender).SelectedValue == (int)grd_jr_cont.Rows[i].Cells["contact_id"].Value &&
                                                            (int)grd_jr_cont.CurrentRow.Cells["job_role_id"].Value == (int)grd_jr_cont.Rows[i].Cells["job_role_id"].Value)
                                                        {
                                                            DataRow c = contacts.Tables["contacts"].Rows.Find(((ComboBox)sender).SelectedValue);
                                                            string cn = c.ItemArray[9].ToString();
                                                            DataRow j = contacts.Tables["job_roles"].Rows.Find(grd_jr_cont.Rows[i].Cells["job_role_id"].Value);
                                                            string jn = j.ItemArray[1].ToString();
                                                            MessageBox.Show("A contact named " + cn +
                                                            " has already been assigned to the job role " + jn + "!",
                                                            "Assignment Already Exist", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                                            ((ComboBox)sender).ResetText();
                                                            grd_jr_cont.CurrentRow.Cells["contact_id"].Value = "";
                                                        }
                                                    }
                                                    grd_jr_cont.CurrentRow.Cells["str_id"].Value = contacts.Tables["projects"].Rows[pi]["str_id"];
                                                    grd_jr_cont.CurrentRow.Cells["contact_id"].Value = ((ComboBox)sender).SelectedValue;
                                                    jrid = (int)grd_jr_cont.CurrentRow.Cells["job_role_id"].Value;
                                                    grd_jr_cont.CurrentRow.Cells["cbo_contacts"].Value = grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                                                    cid = (int)grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                                                    DataRow conta = contacts.Tables["contacts"].Rows.Find(((ComboBox)sender).SelectedValue);
                                                    DataRow compa = contacts.Tables["companies"].Rows.Find(conta.ItemArray[5]);
                                                    DataRow cata = contacts.Tables["categories"].Rows.Find(compa.ItemArray[9]);
                                                    grd_jr_cont.CurrentRow.Cells[5].Value = conta.ItemArray[4];
                                                    grd_jr_cont.CurrentRow.Cells[6].Value = compa.ItemArray[1];
                                                    grd_jr_cont.CurrentRow.Cells[7].Value = compa.ItemArray[2];
                                                    grd_jr_cont.CurrentRow.Cells[8].Value = compa.ItemArray[3];
                                                    grd_jr_cont.CurrentRow.Cells[9].Value = compa.ItemArray[4];
                                                    grd_jr_cont.CurrentRow.Cells[10].Value = compa.ItemArray[5];
                                                    grd_jr_cont.CurrentRow.Cells[11].Value = compa.ItemArray[6];
                                                    grd_jr_cont.CurrentRow.Cells[12].Value = conta.ItemArray[6];
                                                    grd_jr_cont.CurrentRow.Cells[13].Value = compa.ItemArray[7];
                                                    grd_jr_cont.CurrentRow.Cells[14].Value = compa.ItemArray[8];
                                                    grd_jr_cont.CurrentRow.Cells[15].Value = conta.ItemArray[7];
                                                    grd_jr_cont.CurrentRow.Cells[16].Value = conta.ItemArray[8];
                                                    grd_jr_cont.CurrentRow.Cells[17].Value = cata.ItemArray[1];                                                    
                                                }
                                                break;
                                        }
                                    }
                                    break;
                            }
                        }
                        break;
                }
            }
            catch
            { }

            _isdirty = contacts.HasChanges();
        }
        
        //this is the job role add button
        private void add_jr_Click(object sender, EventArgs e)
        {
            mess = new ContactMessage(grd_jr_cont);
            mess.Load += new EventHandler(mess_Load);
            mess.ShowDialog();
        }

        //this is the contact add button
        private void add_cont_Click(object sender, EventArgs e)
        {
            contf = new ContactsAddEdit(contacts, contactsbs, "contacts", grd_jr_cont);
            contf.Load += new EventHandler(contf_Load);
            contf.ShowDialog();

            contf.FormClosed += new FormClosedEventHandler(contf_FormClosed);
            contf.FormClosing += new FormClosingEventHandler(contf_FormClosing);
        }

        //this is the contact edit button
        private void edit_cont_Click(object sender, EventArgs e)
        {
            try
            {
                int cr = grd_jr_cont.CurrentRow.Index;
                grd_jr_cont.CurrentCell = grd_jr_cont.Rows[cr].Cells[1];
                object cid = grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                //DataRow position = contacts.Tables["contacts"].Rows.Find(cid);
                pos = (int)cid;
                contf = new ContactsAddEdit(contacts, contactsbs, pos, "contacts", grd_jr_cont, top, contf);
                //ContactsAddEdit cf = new ContactsAddEdit(contacts, contactsbs, (int)grd_jr_cont.CurrentCell.Value, "contacts", grd_jr_cont);

                contf.Load += new EventHandler(contf_Load);
                contf.ShowDialog();

                contf.FormClosed += new FormClosedEventHandler(contf_FormClosed);
                contf.FormClosing += new FormClosingEventHandler(contf_FormClosing);
            }
            catch
            {
                //MessageBox.Show("You must select a row that contains a contact to enable edit.", "Edit Form Message", MessageBoxButtons.OK);
            }
        }

        //a double click on a contact opens the contact edit form

        private void grd_jr_cont_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        { edit_cont_Click(sender,e); }

        private void grd_jr_cont_CancelRowEdit(object sender, QuestionEventArgs e)
        {

            if (rowinEdit == grd_jr_cont.Rows.Count - 2 && rowinEdit == contacts.Tables["project_contacts"].Rows.Count)
            {

            }
        }

        private void grd_jr_cont_RaiseCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int ci = grd_jr_cont.CurrentCell.ColumnIndex;
            if (ci == 16)
            {
                Outlook.Application ol = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
                Outlook._MailItem olm = (Outlook._MailItem)ol.CreateItem(Outlook.OlItemType.olMailItem);
                string email = (string)grd_jr_cont.CurrentCell.Value;
                olm.To = email;
                olm.Display();
            }
        }

        //this handles deleting rows on the datagridview.  A save is not required...this updates mysql automatically
        private void dgv_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                pcid = (int)grd_jr_cont.CurrentRow.Cells["project_contact_id"].Value;
                pc = contacts.Tables["project_contacts"].Rows.Find(pcid);
                pc.Delete();
                connect.Connect();
                connect.DeleteProjectContacts(pcid, pi);
                connect.Disconnect();
            }
        }

        void mess_Load(object sender, EventArgs e)
        {
            // remobe the event handler here so the garbage collection 
            // can clean up the object when the form is closed.
            // Don't worry new events get hooked when combobox index changes.
            mess.Load -= new EventHandler(mess_Load);
        }

        private void editform(object sender)
        {
            bool nri = (grd_jr_cont.CurrentCell.RowIndex == grd_jr_cont.NewRowIndex);
            int ci = grd_jr_cont.CurrentCell.ColumnIndex;
            cr = grd_jr_cont.CurrentRow;

            switch (ci)
            {
                case 0:
                    {
                        mess = new ContactMessage(grd_jr_cont);
                        mess.Load += new EventHandler(mess_Load);
                        mess.ShowDialog();
                    }
                    break;

                case 1:
                    {
                        try
                        {
                            object cid = grd_jr_cont.CurrentRow.Cells["contact_id"].Value;
                            //DataRow position = contacts.Tables["contacts"].Rows.Find(cid);
                            pos = (int)cid;
                            contf = new ContactsAddEdit(contacts, contactsbs, pos, "contacts", grd_jr_cont, top, contf);
                            ContactsAddEdit cf = new ContactsAddEdit(contacts, contactsbs, (int)grd_jr_cont.CurrentCell.Value, "contacts", grd_jr_cont, top, contf);

                            contf.Load += new EventHandler(contf_Load);
                            contf.ShowDialog();

                            contf.FormClosed += new FormClosedEventHandler(contf_FormClosed);
                            contf.FormClosing += new FormClosingEventHandler(contf_FormClosing);
                        }
                        catch (InvalidCastException e)
                        {
                            Mail.mailman.sendmail("Combo box cast exception", "Method: " + e.TargetSite + Environment.NewLine + "Error Message:" + Environment.NewLine
                    + e.Message + Environment.NewLine + "Call Stack:" + Environment.NewLine + e.StackTrace);
                        }
                    }
                    break;
            }
        }

        private void grd_jr_cont_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (grd_jr_cont.IsCurrentCellDirty)
            {
                grd_jr_cont.CommitEdit(DataGridViewDataErrorContexts.Commit);
                grd_jr_cont.EndEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        void contf_FormClosing(object sender, FormClosingEventArgs e)
        {
            func.FillRows(contacts, grd_jr_cont);
        }

        void contf_FormClosed(object sender, FormClosedEventArgs e)
        {
            Form temp = (Form)sender;
            temp.Dispose();
        }

        void contf_Load(object sender, EventArgs e)
        { }       
        
        public void compe_FormClosing(object sender, FormClosingEventArgs e)
        {
            func.FillRows(contacts, grd_jr_cont);
        }

        public void compe_FormClosed(object sender, FormClosedEventArgs e)
        {}


        private void grd_jr_cont_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {
            //mailman.sendmail("Contacts Grid View Error", anError.Context.ToString());
            //MessageBox.Show("Error happened " + anError.Context.ToString());

            if (anError.Context == DataGridViewDataErrorContexts.Commit)
            {
                int ci = grd_jr_cont.CurrentCell.ColumnIndex;
                int nri = grd_jr_cont.NewRowIndex;
                switch (ci)
                {
                    case 0:
                        {
                            if (grd_jr_cont.CurrentCell.RowIndex == nri)
                            {
                                int csv = (int)grd_jr_cont.CurrentCell.Value;
                                DataRow namerow = contacts.Tables["job_roles"].Rows.Find(csv);
                                string name = (string)namerow.ItemArray[1];
                                if (grd_jr_cont.CurrentCell.ColumnIndex == 0 && name == "<new job role required>")
                                {
                                    grd_jr_cont.CommitEdit(DataGridViewDataErrorContexts.Commit);
                                    grd_jr_cont.EndEdit(DataGridViewDataErrorContexts.Commit);
                                }
                            }
                        }
                        break;
                    case 1:
                        {
                            if (grd_jr_cont.CurrentCell.RowIndex == nri)
                            {
                                int csv = (int)grd_jr_cont.CurrentCell.Value;
                                DataRow namerow = contacts.Tables["contacts"].Rows.Find(csv);
                                string name = (string)namerow.ItemArray[9];
                                if (grd_jr_cont.CurrentCell.ColumnIndex == 1 && name == "<new contact required>")
                                {
                                    grd_jr_cont.CommitEdit(DataGridViewDataErrorContexts.Commit);
                                    grd_jr_cont.EndEdit(DataGridViewDataErrorContexts.Commit);
                                    grd_jr_cont.CurrentCell = grd_jr_cont.CurrentRow.Cells[ci + 1];
                                    grd_jr_cont.CurrentCell = grd_jr_cont.CurrentRow.Cells[ci];
                                }
                            }
                        }
                        break;
                }
            }

            if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
            {
                MessageBox.Show("Cell change");
            }
            if (anError.Context == DataGridViewDataErrorContexts.Parsing)
            {
                MessageBox.Show("parsing error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
            {
                MessageBox.Show("leave control error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.PreferredSize)
            {
                anError.Cancel = true;
            }

            if ((anError.Exception) is ConstraintException)
            {
                DataGridView view = (DataGridView)sender;
                view.Rows[anError.RowIndex].ErrorText = "an error";
                view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";

                anError.ThrowException = false;
            }
        }

        /// <summary>
        /// Event fires when "options" is clicked under the prefereces menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpForm o = new OpForm();
            o.StartPosition = FormStartPosition.CenterParent;
            o.ShowDialog();
        }

        public BindingSource contactbs { get; set; }

        /// <summary>
        /// Event fires when "Feature Request" is click under the  preferences menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void featureRequestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FeatureRequest f = new FeatureRequest();
            f.StartPosition = FormStartPosition.CenterParent;
            f.ShowDialog();
        }

        //this is the save button for the datagridview
        public void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                //OutlookConn conn = new OutlookConn(grd_jr_cont, contacts);
                a = contacts.HasChanges(DataRowState.Added);
                d = contacts.HasChanges(DataRowState.Deleted);
                m = contacts.HasChanges(DataRowState.Modified);
                if (a == false && d == false && m == false)
                {
                    MessageBox.Show("There are no changes to save.", "No Changes To Save", MessageBoxButtons.OK);
                    return;
                }
                connect.Connect();
                connect.LoadProjectContactsComp(ref currentpc);
                int nr = grd_jr_cont.NewRowIndex;
                int strid = (int)cbo_projects.SelectedValue;
                DataRow[] verify = currentpc.Select(string.Format("str_id = '{0}' AND job_role_id = '{1}' AND contact_id = '{2}'",
                    strid, jrid, cid));
                DataRow str = contacts.Tables["projects"].Rows.Find(strid);
                string strnum = str["str_num"].ToString();
                string strseq = str["str_seq"].ToString();
                string strcity = str["str_city"].ToString();
                string strst = str["str_st"].ToString();
                DataRow jobro = contacts.Tables["job_roles"].Rows.Find(jrid);
                string jobrol = jobro["job_role"].ToString();
                DataRow name = contacts.Tables["contacts"].Rows.Find(cid);
                string fullname;
                if (String.IsNullOrEmpty(name["middle_name"].ToString()))
                {
                    fullname = name["first_name"].ToString() + " " + name["last_name"].ToString();
                }
                else
                {
                    fullname = name["first_name"].ToString() + " " + name["middle_name"].ToString() + " " + name["last_name"].ToString();
                }

                int vl = verify.Length;
                if (vl != 0)
                {
                    MessageBox.Show("" + fullname + " has already been assigned the job role of " + jobrol + " on project " +
                        strnum + "-" + strseq + " in " + strcity + " ," + strst + "!" + 
                        "\n\n" + "This assignment most likely made since you pulled your data.", "Job Role Already Assigned", MessageBoxButtons.OK);
                    return;
                }
                MySqlConn con = new MySqlConn(contacts, contacts.Tables["project_contacts"]);
                con.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                connect.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                connect.MysqlPreSave(contacts, contacts.Tables["project_contacts"], grd_jr_cont, original, current, user, id, top);
                //func.FillRows(contacts, grd_jr_cont);
                //connect.Save(contacts.Tables["project_contacts"]);
                //connect.Disconnect();
                func.FillFolders(contacts, grd_jr_cont, pi);

                               
                //if (Properties.Settings.Default.STORE_COUNT == contacts.Tables["projects"].Rows.Count)
                //{ func.FolderView(contacts); }
                //else if (Properties.Settings.Default.STORE_COUNT > contacts.Tables["projects"].Rows.Count)
                //{
                //    Properties.Settings.Default.STORE_COUNT = contacts.Tables["projects"].Rows.Count;
                //    Properties.Settings.Default.Save();
                //}
                //else
                //{
                //    func.FolderView(contacts);                     
                //    Properties.Settings.Default.STORE_COUNT = contacts.Tables["projects"].Rows.Count;
                //    Properties.Settings.Default.Save();
                //}               
                
                MessageBox.Show("Save was successful!", "Save Is Wonderful.  Whew!");
            }            
            
            catch (System.Exception ex)
            {
                Mail.mailman.sendmail("MySql Save button Error", "Method: " + ex.TargetSite + Environment.NewLine + "Error Message:" + Environment.NewLine
                    + ex.Message + Environment.NewLine + "Call Stack:" + Environment.NewLine + ex.StackTrace);
            }
        }

        private void but_email_Click(object sender, EventArgs e)
        {
            StringBuilder sbto = new StringBuilder();
            StringBuilder sbcc = new StringBuilder();
            StringBuilder sbbc = new StringBuilder();
            StringBuilder subj = new StringBuilder();

            for (int i = 0; i < grd_jr_cont.Rows.Count - 1; i++)
            {
                DataGridViewRow row = grd_jr_cont.Rows[i];

                for (int c = 2; c < 5; c++)
                {
                    DataGridViewCell cell = grd_jr_cont.Rows[i].Cells[c];
                    string name = cell.OwningColumn.Name;

                    if ((bool)row.Cells[name].EditedFormattedValue == true)
                    {
                        DataGridViewLinkCell lc = (DataGridViewLinkCell)row.Cells["tbo_email"];
                        string email = lc.EditedFormattedValue.ToString();

                        switch (name)
                        {
                            case "to":
                                {
                                    int sbl = sbto.Length;
                                    if (sbl == 0)
                                    {sbto.Insert(0, email);}
                                    else
                                    {sbto.Append("; " + email);}                                    
                                }
                                break;
                            case "cc":
                                {
                                    int sbl = sbcc.Length;
                                    if (sbl == 0)
                                    { sbcc.Insert(0, email); }
                                    else
                                    { sbcc.Append("; " + email);}                                    
                                }
                                break;
                            case "bc":
                                {
                                    int sbl = sbbc.Length;
                                    if (sbl == 0)
                                    { sbbc.Insert(0, email); }
                                    else
                                    { sbbc.Append("; " + email);}                                   
                                }
                                break;
                        }                              
                    }
                }                
            }

            tostr = sbto.ToString();
            ccstr = sbcc.ToString();
            bcstr = sbbc.ToString();
            Outlook.Application ol = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
            Outlook._MailItem olm = (Outlook._MailItem)ol.CreateItem(Outlook.OlItemType.olMailItem);
            olm.To = tostr;
            olm.CC = ccstr;
            olm.BCC = bcstr;
            subj.Insert(0, tbo_str_num.Text);
            subj.Append("-" + tbo_str_seq.Text + " " + tbo_str_city.Text + ", " + tbo_str_st.Text + " -");
            olm.Subject = subj.ToString();
            olm.Display(); 
        }

        void con_StatmentCompleted(string SqlStatement)
        {}

        public AutoCompleteMode AutoCompleteMode { get; set; }        
    }
}